package com.wcgksoft.controller.att_management;

import com.wcgksoft.common.util.Layui;
import com.wcgksoft.entity.Att_management.Att_management;
import com.wcgksoft.entity.Att_management.Healthy_statistics;
import com.wcgksoft.entity.system.EnterpriseProject;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.service.Att_management.Healthy_statisticsService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 周权
 * @Date: 2020/03/18/13:15
 * @Description:健康月逐日统计
 */
@Controller
@RequestMapping(value = "system/healthy_statistics")
public class Healthy_statisticsController {

    @Autowired
    private Healthy_statisticsService healthy_statisticsService;
    /*
     * @Author: 周权
     * @Description:健康系统逐日统计列表
     * @Param:
     * @create: 2020/3/18 10:21
     * @return:
     */
    @ResponseBody
    @RequestMapping(value = "findHealthy_month")
    public Layui findHealthy_month(@RequestParam(value = "e_id", required = false) Integer e_id,
                                   @RequestParam(value = "a_tid", required = false) Integer a_tid,
                                   @RequestParam(value = "role_id", required = false) Integer role_id,
                                   @RequestParam(value = "area_id", required = false) Integer area_id,
                                   @RequestParam(value = "page", required = false) Integer page,
                                   @RequestParam(value = "limit", required = false) Integer limit,
                                   @RequestParam(value = "starttime", required = false) String starttime,
                                   @RequestParam(value = "h_team", required = false) String h_team) throws ParseException {
        DetachedCriteria criteria = DetachedCriteria.forClass(Healthy_statistics.class);
        if (null!=h_team&&!"".equals(h_team)) {
            criteria.add(Restrictions.like("s_team", h_team, MatchMode.ANYWHERE));
        }
        if(null!=starttime&&!"".equals(starttime)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = sdf.parse(starttime+"-01 00:00:00");
            Date parse2 = sdf.parse(starttime+"-31 23:59:99");
            criteria.add(Restrictions.between("s_createDate", parse, parse2));
        }
        if(role_id==2){
            criteria.add(Restrictions.eq("s_eid", e_id));
        } else if(role_id==3){
            criteria.add(Restrictions.eq("s_eid", e_id));
            criteria.add(Restrictions.eq("s_area_id", area_id));
        }else if(role_id==4){
            criteria.add(Restrictions.eq("s_tid", a_tid));
        }
        criteria.addOrder(Order.asc("s_team"));
        criteria.addOrder(Order.asc("s_createDate"));
        List<Healthy_statistics> byConditions = healthy_statisticsService.findByConditions(criteria,page,limit);
        return Layui.data(0, "查询成功", healthy_statisticsService.getTotalCount(),byConditions);
    }

    /*
     * @Author: 周权
     * @Description: 健康统计逐日表头
     * @Param:
     * @create: 2020/3/18 10:45
     * @return:
     */
    @ResponseBody
    @RequestMapping(value = "findCols")
    public Layui findCols(@RequestParam(value = "a_tid", required = false) Integer a_tid,
                          @RequestParam(value = "starttime", required = false) String starttime,
                          @RequestParam(value = "h_team", required = false) String h_team,
                          @RequestParam(value = "e_id", required = false) Integer e_id,
                          @RequestParam(value = "area_id", required = false) Integer area_id,
                          @RequestParam(value = "role_id", required = false) Integer role_id) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Healthy_statistics.class);
        criteria.addOrder(Order.asc("s_team"));
        criteria.addOrder(Order.asc("s_createDate"));
        if(role_id==2){
            if(null!=h_team&&!"".equals(h_team)){
                criteria.add(Restrictions.like("s_team", h_team, MatchMode.ANYWHERE));
            }
            if(null!=starttime&&!"".equals(starttime)){
                criteria.add(Restrictions.sqlRestriction("DATE_FORMAT(createDate,'%Y-%m')= '"+starttime+"'"));
            }
            criteria.add(Restrictions.eq("s_eid", e_id));
            List<Healthy_statistics> byConditions = healthy_statisticsService.findByConditions(criteria);
            return Layui.data(0, "查询成功", healthy_statisticsService.getTotalCount(), byConditions);
        } else if(role_id==3){
            if(null!=h_team&&!"".equals(h_team)){
                criteria.add(Restrictions.like("s_team", h_team, MatchMode.ANYWHERE));
            }
            if(null!=starttime&&!"".equals(starttime)){
                criteria.add(Restrictions.sqlRestriction("DATE_FORMAT(createDate,'%Y-%m')= '"+starttime+"'"));
            }
            criteria.add(Restrictions.eq("s_eid", e_id));
            criteria.add(Restrictions.eq("s_area_id", area_id));
            List<Healthy_statistics> byConditions = healthy_statisticsService.findByConditions(criteria);
            return Layui.data(0, "查询成功", healthy_statisticsService.getTotalCount(), byConditions);
        } else if(role_id==4){
            criteria.add(Restrictions.eq("s_tid", a_tid));
            List<Healthy_statistics> byConditions = healthy_statisticsService.findByConditions(criteria);
            return Layui.data(0, "查询成功", healthy_statisticsService.getTotalCount(), byConditions);
        }
        return Layui.data(0,null,null);
    }

    /*
    * @Author: 周权
    * @Description: 健康统计逐日柱状图
    * @Param:
    * @create: 2020/3/18 21:08
    * @return:
    */
    @ResponseBody
    @RequestMapping(value = "statis")
    public HashMap statis(@RequestParam(value = "a_tid", required = false) Integer a_tid,
                          @RequestParam(value = "e_id", required = false) Integer e_id,
                          @RequestParam(value = "area_id", required = false) Integer area_id,
                          @RequestParam(value = "role_id", required = false) Integer role_id,
                          @RequestParam(value = "starttime", required = false) String starttime,
                          @RequestParam(value = "h_team", required = false) String h_team) throws ParseException {
        DetachedCriteria criteria = DetachedCriteria.forClass(Healthy_statistics.class);
        if (null!=h_team&&!"".equals(h_team)) {
            criteria.add(Restrictions.like("s_team", h_team, MatchMode.ANYWHERE));
        }
        if(null!=starttime&&!"".equals(starttime)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = sdf.parse(starttime+"-01 00:00:00");
            Date parse2 = sdf.parse(starttime+"-31 23:59:99");
            criteria.add(Restrictions.between("s_createDate", parse, parse2));
        }
        if(role_id==2){
            criteria.add(Restrictions.eq("s_eid", e_id));
        } else if(role_id==3){
            criteria.add(Restrictions.eq("s_eid", e_id));
            criteria.add(Restrictions.eq("s_area_id", area_id));
        } else if(role_id==4){
            criteria.add(Restrictions.eq("s_tid", a_tid));
        }
        List<Healthy_statistics> byConditions = healthy_statisticsService.findByConditions(criteria);
        if(byConditions.size()>0){
            HashMap map = new HashMap<>();
            List<Integer> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            if (null!=h_team&&!"".equals(h_team)) {
                String teamName=null;
                for(int l =0;l<byConditions.size();l++){
                    if(null==teamName){
                        teamName = byConditions.get(l).getS_team();
                    }
                }
                map.put("team", teamName);//map装入查询的队伍名称
            }

            if(null!=starttime&&!"".equals(starttime)) {
                String lastDayOfMonth = getLastDayOfMonth(starttime);
                Calendar cal = Calendar.getInstance();//新建日历类
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//格式化年-月-日
                Date parse = dateFormat.parse(lastDayOfMonth);//查询月份显示查询日期柱状图
                cal.setTime(parse);//日历设置当前时间
                int year = cal.get(Calendar.YEAR);//获得年
                int month = cal.get(Calendar.MONTH) + 1;//获得月
                String yea = String.valueOf(year);//年转字符串
                String mon = String.valueOf(month);//月转字符串
                int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//获得当月最大日期
                int minDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);//获得当月最小日期
                for (int i = minDay; i <= maxDay; i++) {//循环当月所有天数
                    String workday;
                    if (i < 10) {//如果日期当天小于10（一位数）
                        if (month < 10) {//如果当前月份小于十（一位数）
                            workday = yea + "-0" + mon + "-0" + i;//拼接字符串 xxxx-0x-0x
                        } else {
                            workday = yea + "-" + mon + "-0" + i;//月份两位数 xxxx-xx-0x
                        }
                    } else {//日期当天大于等于10（两位数）
                        if (month < 10) {//如果当前月份小于十（一位数）
                            workday = yea + "-0" + mon + "-" + i;//拼接字符串 xxxx-0x-xx
                        } else {
                            workday = yea + "-" + mon + "-" + i;//月份两位数 xxxx-xx-xx
                        }
                    }
                    DetachedCriteria c1 = DetachedCriteria.forClass(Healthy_statistics.class);//离线查询考勤
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date parse3 = sdf.parse(workday+" 00:00:00");
                    Date parse4 = sdf.parse(workday+" 23:59:99");
                    c1.add(Restrictions.between("s_createDate", parse3, parse4));
                    if (null!=h_team&&!"".equals(h_team)) {
                        c1.add(Restrictions.like("s_team", h_team, MatchMode.ANYWHERE));
                    }
                    if(role_id==2){
                        c1.add(Restrictions.eq("s_eid", e_id));
                    } else if(role_id==3){
                        c1.add(Restrictions.eq("s_eid", e_id));
                        c1.add(Restrictions.eq("s_area_id", area_id));
                    } else if(role_id==4){
                        c1.add(Restrictions.eq("s_tid", a_tid));
                    }
                    List<Healthy_statistics> by1 = healthy_statisticsService.findByConditions(c1);//获得符合条件集合
                    if (by1.size() > 0) {//有符合条件数据
                        int sum = 0;//定义sum用于存放当天异常总值
                        for (int s =0;s<by1.size();s++) {//循环健康集合
                            if (null != by1.get(s).getS_no_num()) {//异常人数不为空
                                sum +=by1.get(s).getS_no_num();//异常人数累加
                            }else{
                                sum = sum+0;
                            }
                        }
                        list1.add(sum);//将异常数装入list1
                    } else {//无符合条件数据
                        list1.add(0);//当月无数据 每天都存0
                    }
                    String md = mon + "-" + i;//拼接字符串 xx-x||xx-xx
                    list2.add(md);//循环装入list2（日期集合）
                }
                map.put("worklist", list1);//map装入list1
                map.put("daylist", list2);//map装入list2
                map.put("month", mon);//map装入查询的月份
                return map;
            }else{
                Calendar cal = Calendar.getInstance();//新建日历类
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//格式化年-月-日
                Date parse = dateFormat.parse(dateFormat.format(new Date()));//不查询月份默认显示新建日期（当月）柱状图
                cal.setTime(parse);//日历设置当前时间
                int year = cal.get(Calendar.YEAR);//获得年
                int month = cal.get(Calendar.MONTH) + 1;//获得月
                String yea = String.valueOf(year);//年转字符串
                String mon = String.valueOf(month);//月转字符串
                int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//获得当月最大日期
                int minDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);//获得当月最小日期
                for (int i = minDay; i <= maxDay; i++) {//循环当月所有天数
                    String workday = null;
                    if (i < 10) {//如果日期当天小于10（一位数）
                        if (month < 10) {//如果当前月份小于十（一位数）
                            workday = yea + "-0" + mon + "-0" + i;//拼接字符串 xxxx-0x-0x
                        } else {
                            workday = yea + "-" + mon + "-0" + i;//月份两位数 xxxx-xx-0x
                        }
                    } else {//日期当天大于等于10（两位数）
                        if (month < 10) {//如果当前月份小于十（一位数）
                            workday = yea + "-0" + mon + "-" + i;//拼接字符串 xxxx-0x-xx
                        } else {
                            workday = yea + "-" + mon + "-" + i;//月份两位数 xxxx-xx-xx
                        }
                    }
                    DetachedCriteria c1 = DetachedCriteria.forClass(Healthy_statistics.class);//离线查询考勤
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date parse3 = sdf.parse(workday+" 00:00:00");
                    Date parse4 = sdf.parse(workday+" 23:59:99");
                    c1.add(Restrictions.between("s_createDate", parse3, parse4));
                    if (null!=h_team&&!"".equals(h_team)) {
                        c1.add(Restrictions.like("s_team", h_team, MatchMode.ANYWHERE));
                    }
                    if(role_id==2){
                        c1.add(Restrictions.eq("s_eid", e_id));
                    } else if(role_id==3){
                        c1.add(Restrictions.eq("s_eid", e_id));
                        c1.add(Restrictions.eq("s_area_id", area_id));
                    } else if(role_id==4){
                        c1.add(Restrictions.eq("s_tid", a_tid));
                    }
                    List<Healthy_statistics> by1 = healthy_statisticsService.findByConditions(c1);//获得符合条件集合
                    if (by1.size() > 0) {//有符合条件数据
                        int sum = 0;//定义sum用于存放当天异常人数总值
                        for (int s =0;s<by1.size();s++) {//循环健康集合
                            if (null != by1.get(s).getS_no_num()) {//异常人数不为空
                                sum +=by1.get(s).getS_no_num();//异常人数累加
                            }else{
                                sum = sum+0;
                            }
                        }
                        list1.add(sum);//将总异常数装入list1
                    } else {//无符合条件数据
                        list1.add(0);//当月无数据 每天都存0
                    }
                    String md = mon + "-" + i;//拼接字符串 xx-x||xx-xx
                    list2.add(md);//循环装入list2（日期集合）
                }
                map.put("worklist", list1);//map装入list1
                map.put("daylist", list2);//map装入list2
                map.put("month", mon);//map装入查询的月份
                return map;
            }
        }else{
            HashMap map = new HashMap<>();
            List<Integer> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            Calendar cal = Calendar.getInstance();//新建日历类
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//格式化年-月-日
            Date parse = dateFormat.parse(dateFormat.format(new Date()));//不查询月份默认显示新建日期（当月）柱状图
            cal.setTime(parse);//日历设置当前时间
            int month = cal.get(Calendar.MONTH) + 1;//获得月
            String mon = String.valueOf(month);//月转字符串
            int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//获得当月最大日期
            int minDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);//获得当月最小日期
            for (int i = minDay; i <= maxDay; i++) {//循环当月所有天数
                list1.add(0);//当月无签到数据 每天都存0
                String md = mon + "-" + i;//拼接字符串 xx-x||xx-xx
                list2.add(md);//循环装入list2（日期集合）
            }
            map.put("worklist", list1);//map装入list1
            map.put("daylist", list2);//map装入list2
            map.put("month", mon);//map装入查询的月份
            map.put("team", "暂无施工队");//map装入查询的队伍名称
            return map;
        }
    }

    /*
     * @Author: 周权
     * @Description:获得当前月份天数
     * @Param:
     * @create: 2020/3/12 16:57
     * @return:
     */
    public static String getLastDayOfMonth(String yearMonth) {
        int year = Integer.parseInt(yearMonth.split("-")[0]);  //年
        int month = Integer.parseInt(yearMonth.split("-")[1]); //月
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置月份
        // cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.MONTH, month); //设置当前月的上一个月
        // 获取某月最大天数
        //int lastDay = cal.getActualMaximum(Calendar.DATE);
        int lastDay = cal.getMinimum(Calendar.DATE); //获取月份中的最小值，即第一天
        // 设置日历中月份的最大天数
        //cal.set(Calendar.DAY_OF_MONTH, lastDay);
        cal.set(Calendar.DAY_OF_MONTH, lastDay - 1); //上月的第一天减去1就是当月的最后一天
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /*
    * @Author: 周权
    * @Description:首页健康统计曲线图
    * @Param:
    * @create: 2020/3/30 14:59
    * @return:
    */
    @ResponseBody
    @RequestMapping(value = "admin_healthy_static")
    public HashMap admin_healthy_static() throws ParseException {
        DetachedCriteria criteria = DetachedCriteria.forClass(Healthy_statistics.class);
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
        Session session = SecurityUtils.getSubject().getSession();
        Integer id1 = sysUser.getSysRole().getSysRoleCode().getId();
        if(id1==2){
            Integer id = sysUser.getEnterprise().getId();
            criteria.add(Restrictions.eq("s_eid", id));
        }else if(id1==3){
            Integer id = sysUser.getEnterprise().getId();
            EnterpriseProject enterpriseProject = (EnterpriseProject)session.getAttribute("area");
            Integer id2 = enterpriseProject.getId();
            criteria.add(Restrictions.eq("s_eid", id));
            criteria.add(Restrictions.eq("s_area_id", id2));
        }else if(id1==4){
            Integer id = sysUser.getEnterprise().getId();
            Integer team_id = sysUser.getTeam_id();
            criteria.add(Restrictions.eq("s_eid", id));
            criteria.add(Restrictions.eq("s_tid", team_id));
        }
        List<Healthy_statistics> byConditions = healthy_statisticsService.findByConditions(criteria);
        if(byConditions.size()>0){
            HashMap map = new HashMap<>();
            List<Integer> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            Calendar cal = Calendar.getInstance();//新建日历类
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//格式化年-月-日
            Date parse = dateFormat.parse(dateFormat.format(new Date()));//不查询月份默认显示新建日期（当月）柱状图
            cal.setTime(parse);//日历设置当前时间
            int year = cal.get(Calendar.YEAR);//获得年
            int month = cal.get(Calendar.MONTH) + 1;//获得月
            String yea = String.valueOf(year);//年转字符串
            String mon = String.valueOf(month);//月转字符串
            int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//获得当月最大日期
            int minDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);//获得当月最小日期
            for (int i = minDay; i <= maxDay; i++) {//循环当月所有天数
                String workday = null;
                if (i < 10) {//如果日期当天小于10（一位数）
                    if (month < 10) {//如果当前月份小于十（一位数）
                        workday = yea + "-0" + mon + "-0" + i;//拼接字符串 xxxx-0x-0x
                    } else {
                        workday = yea + "-" + mon + "-0" + i;//月份两位数 xxxx-xx-0x
                    }
                } else {//日期当天大于等于10（两位数）
                    if (month < 10) {//如果当前月份小于十（一位数）
                        workday = yea + "-0" + mon + "-" + i;//拼接字符串 xxxx-0x-xx
                    } else {
                        workday = yea + "-" + mon + "-" + i;//月份两位数 xxxx-xx-xx
                    }
                }
                DetachedCriteria c1 = DetachedCriteria.forClass(Healthy_statistics.class);//离线查询考勤
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parse3 = sdf.parse(workday+" 00:00:00");
                Date parse4 = sdf.parse(workday+" 23:59:99");
                c1.add(Restrictions.between("s_createDate", parse3, parse4));
                if(id1==2){
                    Integer id = sysUser.getEnterprise().getId();
                    criteria.add(Restrictions.eq("s_eid", id));
                }else if(id1==3){
                    Integer id = sysUser.getEnterprise().getId();
                    EnterpriseProject enterpriseProject = (EnterpriseProject)session.getAttribute("area");
                    Integer id2 = enterpriseProject.getId();
                    criteria.add(Restrictions.eq("s_eid", id));
                    criteria.add(Restrictions.eq("s_area_id", id2));
                }else if(id1==4){
                    Integer id = sysUser.getEnterprise().getId();
                    Integer team_id = sysUser.getTeam_id();
                    criteria.add(Restrictions.eq("s_eid", id));
                    criteria.add(Restrictions.eq("s_tid", team_id));
                }
                List<Healthy_statistics> by1 = healthy_statisticsService.findByConditions(c1);//获得符合条件集合
                if (by1.size() > 0) {//有符合条件数据
                    int sum = 0;//定义sum用于存放当天异常人数总值
                    for (int s =0;s<by1.size();s++) {//循环健康集合
                        if (null != by1.get(s).getS_no_num()) {//异常人数不为空
                            sum +=by1.get(s).getS_no_num();//异常人数累加
                        }else{
                            sum = sum+0;
                        }
                    }
                    list1.add(sum);//将总异常数装入list1
                } else {//无符合条件数据
                    list1.add(0);//当月无数据 每天都存0
                }
                String md = mon + "-" + i;//拼接字符串 xx-x||xx-xx
                list2.add(md);//循环装入list2（日期集合）
            }
            map.put("worklist", list1);//map装入list1
            map.put("daylist", list2);//map装入list2
            return map;
        }else{
            HashMap map = new HashMap<>();
            List<Integer> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            Calendar cal = Calendar.getInstance();//新建日历类
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//格式化年-月-日
            Date parse = dateFormat.parse(dateFormat.format(new Date()));//不查询月份默认显示新建日期（当月）柱状图
            cal.setTime(parse);//日历设置当前时间
            int month = cal.get(Calendar.MONTH) + 1;//获得月
            String mon = String.valueOf(month);//月转字符串
            int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//获得当月最大日期
            int minDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);//获得当月最小日期
            for (int i = minDay; i <= maxDay; i++) {//循环当月所有天数
                list1.add(0);//当月无签到数据 每天都存0
                String md = mon + "-" + i;//拼接字符串 xx-x||xx-xx
                list2.add(md);//循环装入list2（日期集合）
            }
            map.put("worklist", list1);//map装入list1
            map.put("daylist", list2);//map装入list2
            return map;
        }
    }
}
